package com.sylvek.sentinel.servlet;

import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.GeocellQuery;
import com.beoui.geocell.model.Point;
import com.sylvek.sentinel.Emergency;
import com.sylvek.sentinel.PersistenceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sylvek
 * 
 */
public class UpdateLocation extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        final String latitude = req.getParameter("latitude");
        if (latitude == null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        final double lat = Double.parseDouble(latitude);

        final String longitude = req.getParameter("longitude");
        if (longitude == null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        final double lon = Double.parseDouble(longitude);

        final String category = req.getParameter("category");

        final String dist = req.getParameter("distance");
        double distance = 500;
        if (dist != null) {
            distance = Double.parseDouble(dist);
        }

        final String timeout = req.getParameter("age");
        long age = TimeUnit.MINUTES.toMillis(10L);
        if (timeout != null) {
            age = Long.parseLong(timeout);
        }

        final Point center = new Point(lat, lon);
        final PersistenceManager pm = PersistenceFactory.getManager();

        List<Object> params = new ArrayList<Object>();
        params.add(System.currentTimeMillis() - age);

        StringBuilder query = new StringBuilder("time > lessThanTen");
        StringBuilder param = new StringBuilder("Long lessThanTen");
        if (category != null) {
            query.append(" && category == myCategory");
            param.append(", String myCategory");
            params.add(category);
        }

        GeocellQuery baseQuery = new GeocellQuery(query.toString(), param.toString(), params);
        final List<Emergency> emergencies = GeocellManager.proximitySearch(center, 40, distance, Emergency.class, baseQuery, pm);

        resp.setHeader("Content-Type", "application/json; charset=iso-8859-15");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.getWriter().print(emergencies.size());
    }
}
